﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace BusinessDll
{
    public class WriteLog
    {
        //默认路劲
        public static string rootPath = "c:\\hk_log\\";
        private static Object obInfo = new Object();
        private static Object obDebug = new Object();
        public static void WriteLogs(string module, string info)
        {
            lock (obInfo) { 
                WriteLogsCommon(module,info,"info");
            }
        }
        public static void showOnUI(string module, string info) {
            string logTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            lock (GlobalInfo.Instance.logLock) {
                viewEntity viewEntity = new viewEntity(logTime, module, info);
                GlobalInfo.Instance.viewEntities.AddLast(viewEntity);
            }
            WriteLogs(module,info);
            //GlobalInfo.Instance.businessControl.showOnUI(module,info);
        }
        public static void WriteDebugLogs(string module, string info) {
            lock (obDebug)
            {
                WriteLogsCommon(module, info, "debug"); 
            }
        }
        public static void printException(Exception ex)
        {
            WriteLogs("异常机制", "exception is " + ex.Message);
            WriteLogs("异常机制", "exception is " + ex.StackTrace);
        }
        public static void WriteLogsCommon(string module, string info, string _filePath)
        {
            string logTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            string logShortTime = DateTime.Now.ToString("yyyy-MM-dd");
            FileStream fs = null;
            StreamWriter writer = null;
            FileMode fileMode = 0;
            try
            {
                if (File.Exists(rootPath +  logShortTime + _filePath + ".log"))
                {
                    fileMode = FileMode.Append;
                }
                else
                {
                    fileMode = FileMode.CreateNew;
                }
                fs = new FileStream(rootPath + logShortTime + _filePath + ".log", fileMode);
                
                writer = new StreamWriter(fs);
                writer.WriteLine(logTime + "  " + module + " :" + info);
                
            }
            catch (Exception e)
            {
                printException(e);
            }
            finally
            {
                if (writer != null)
                    writer.Close();
                if (fs != null)
                    fs.Close();
            }
        }
    }
}
